package com.ruoyi.electronicFence.service.Impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ruoyi.common.GenericMethods;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.electronicFence.domain.MonitoringParameters;
import com.ruoyi.electronicFence.domain.TDeviceInfoModificationHistory;
import com.ruoyi.electronicFence.domain.TEquipmentMonitorDevice;
import com.ruoyi.electronicFence.mapper.TDeviceInfoModificationHistoryMapper;
import com.ruoyi.electronicFence.mapper.TEquipmentMonitorDeviceMapper;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.electronicFence.mapper.TDeviceStatusMapper;
import com.ruoyi.electronicFence.domain.TDeviceStatus;
import com.ruoyi.electronicFence.service.ITDeviceStatusService;

/**
 * 设备状态Service业务层处理
 *
 * @author sxygsj
 * @date 2024-05-17
 */
@Service
public class TDeviceStatusServiceImpl implements ITDeviceStatusService
{
    @Autowired
    private TDeviceStatusMapper tDeviceStatusMapper;
    @Autowired
    TEquipmentMonitorDeviceMapper tEquipmentMonitorDeviceMapper;
    @Autowired
    TDeviceInfoModificationHistoryMapper tDeviceInfoModificationHistoryMapper;

    /**
     * 查询设备状态
     *
     * @param id 设备状态主键
     * @return 设备状态
     */
    @Override
    public TDeviceStatus selectTDeviceStatusById(Long id)
    {
        return tDeviceStatusMapper.selectTDeviceStatusById(id);
    }

    /**
     * 查询设备状态列表
     *
     * @param tDeviceStatus 设备状态
     * @return 设备状态
     */
    @Override
    public List<TDeviceStatus> selectTDeviceStatusList(TDeviceStatus tDeviceStatus)
    {
        return tDeviceStatusMapper.selectTDeviceStatusList(tDeviceStatus);
    }

    /**
     * 新增设备状态
     *
     * @param tDeviceStatus 设备状态
     * @return 结果
     */
    @Override
    public AjaxResult insertTDeviceStatus(TDeviceStatus tDeviceStatus)
    {
        //检查控制器的设备名称是否重复
        TDeviceStatus deviceName = new TDeviceStatus();
        deviceName.setDeviceName(tDeviceStatus.getDeviceName());
        List<TDeviceStatus> tDeviceStatuses = tDeviceStatusMapper.selectTDeviceStatusList(deviceName);
        if (tDeviceStatuses.size()>0){
            return AjaxResult.error("监测设备名称不可重复添加失败");
        }
        String  DeviceId= GenericMethods.convertIpToNumeric(tDeviceStatus.getDeviceIp());
        tDeviceStatus.setDeviceId(DeviceId);
        int i = tDeviceStatusMapper.insertTDeviceStatus(tDeviceStatus);
        if (i>0){
            return AjaxResult.success("新增成功");

        }else {
            return AjaxResult.error("新增异常");

        }

    }

    /**
     * 修改设备状态
     *
     * @param tDeviceStatus 设备状态
     * @return 结果
     */
    @Override
    public AjaxResult updateTDeviceStatus(TDeviceStatus tDeviceStatus)
    {

        String DeviceIdOld = tDeviceStatus.getDeviceId();
        String  DeviceId= GenericMethods.convertIpToNumeric(tDeviceStatus.getDeviceIp());
        tDeviceStatus.setDeviceId(DeviceId);
        int i = tDeviceStatusMapper.updateTDeviceStatus(tDeviceStatus);
        if (i>0){

            TEquipmentMonitorDevice tEquipmentMonitorDevice = new TEquipmentMonitorDevice();
            tEquipmentMonitorDevice.setMonitorDeviceId(tDeviceStatus.getDeviceId());
            tEquipmentMonitorDevice.setMonitorDeviceIdOld(DeviceIdOld);
            tEquipmentMonitorDeviceMapper.updateTEquipmentMonitorDeviceByMonitorDeviceId(tEquipmentMonitorDevice);
            //修改后 继续更新 监测设备和场所关联表
            return AjaxResult.success("修改成功");

        }else {
            return AjaxResult.error("修改异常");

        }
    }

    @Override
    public int synchronousUpdate(TDeviceStatus tDeviceStatus) {


        return tDeviceStatusMapper.synchronousUpdate(tDeviceStatus);
    }

    /**
     * 批量删除设备状态
     *
     * @param ids 需要删除的设备状态主键
     * @return 结果
     */
    @Override
    public int deleteTDeviceStatusByIds(Long[] ids)
    {
        Long id = ids[0];
        TDeviceStatus tDeviceStatus = tDeviceStatusMapper.selectTDeviceStatusById(id);
        int i = tDeviceStatusMapper.deleteTDeviceStatusById(tDeviceStatus.getId());
        if (i>0){
            TEquipmentMonitorDevice tEquipmentMonitorDevice = new TEquipmentMonitorDevice();
            tEquipmentMonitorDevice.setMonitorDeviceId(tDeviceStatus.getDeviceId());
            tEquipmentMonitorDeviceMapper.deleteTEquipmentMonitorDeviceByMonitorDeviceId(tEquipmentMonitorDevice);
        }
        return i ;
    }

    /**
     * 删除设备状态信息
     *
     * @param id 设备状态主键
     * @return 结果
     */
    @Override
    public int deleteTDeviceStatusById(Long id)
    {

        return tDeviceStatusMapper.deleteTDeviceStatusById(id);
    }

    @Override
    public int deleteTEquipmentMonitorDeviceByMonitorDeviceId(TDeviceStatus tDeviceStatus) {

        int i = tDeviceStatusMapper.deleteTDeviceStatusById(tDeviceStatus.getId());
        if (i>0){
            TEquipmentMonitorDevice tEquipmentMonitorDevice = new TEquipmentMonitorDevice();
            tEquipmentMonitorDevice.setMonitorDeviceId(tDeviceStatus.getDeviceId());
            tEquipmentMonitorDeviceMapper.deleteTEquipmentMonitorDeviceByMonitorDeviceId(tEquipmentMonitorDevice);
        }
        return i ;
    }

    @Override
    public Map<String, Object> selectSettingsList(String Type,String IP) {

        String ip = GenericMethods.convertIpToNumeric(IP);
        TDeviceStatus deviceStatus = new TDeviceStatus();
        deviceStatus.setDeviceIp(IP);
        List<TDeviceStatus> tDeviceStatuses = tDeviceStatusMapper.selectTDeviceStatusList(deviceStatus);
        TDeviceStatus deviceStatus1 = tDeviceStatuses.get(0);
        String Status = deviceStatus1.getDeviceStatus();
        if (Status.equals("在线")){
            String url ="";
            if (StringUtils.isEmpty(Type)){
                Type="PERSON";
            }
            url="http://"+IP+":8080/electronicFence/readParam";
            url=url+"?model="+Type;
            // 发送 GET 请求并获取响应
            HttpResponse<String> response = Unirest.get(url)
                    .header("Content-Type", "application/json")
                    .header("Accept", "*/*")
                    .header("Host", IP+":8080")
                    .header("Connection", "keep-alive")
                    .asString();


            String body = response.getBody(); // 将 JSON 字符串转换为 JSONObject
            JSONObject jsonObject = new JSONObject(body);

            // 将 JSONObject 转换为 Map
            Map<String, Object> map = new JSONObject(body).toMap();
            Map<String,Object> value = (Map<String,Object>)map.get("Value");
            String whitelist = (String)value.get("WHITELIST");

            if (StringUtils.isNotEmpty(whitelist)){
                // 将字符串按照分隔符 "|" 分割成字符串数组
                String[] whitelistArray = whitelist.split("\\|");
                value.put("WHITELIST",whitelistArray);
            }
            return map;
        }else {
            HashMap<String, Object> map2 = new HashMap<>();
            map2.put("msg","设备离线，无法查看详情");
            map2.put("code",500);
            return map2;
        }



    }

    @Override
    public Map<String, Object> updateSettingsList(Map<String, Object> monitoringParameters) {


        HashMap<String, Object> map1 = new HashMap<>();

        String url ="";
        String IP = (String) monitoringParameters.get("ControllerIP");
        Map<String,Object> value = (Map<String,Object>)monitoringParameters.get("Value");
        ArrayList<String> arrayList = new ArrayList<>();
        Object whitelist = value.get("WHITELIST");
        if (whitelist!=null && StringUtils.isNotEmpty(whitelist.toString())){
            arrayList = (ArrayList<String>)value.get("WHITELIST");
            StringBuilder joinedWhitelist = new StringBuilder();
            for (int i = 0; i < arrayList.size(); i++) {
                joinedWhitelist.append(arrayList.get(i));
                if (i < arrayList.size() - 1) {
                    joinedWhitelist.append("|"); // 添加分隔符
                }
            }
            value.put("WHITELIST",joinedWhitelist);
        }


        String Type = "PERSON";
        if (StringUtils.isEmpty(Type)){
            Type="PERSON";
        }

        // 创建 JSON 对象作为请求体
//        JSONObject requestBody = new JSONObject();
//        requestBody.put("ALARMDISTANCE", monitoringParameters.get()");
//        requestBody.put("DRIVERDISTANCE", "value2");
//        requestBody.put("MAXNUMBERSOFPERSON", "value2");
//        requestBody.put("MINNUMBERSOFPERSON", "value2");
//        requestBody.put("SHUTDOWNDISTANCE", "value2");
//        requestBody.put("WHITELIST", "value2");


        url="http://"+IP+":8080/electronicFence/writeParam";
        url=url+"?model="+Type;


        // 发送 POST 请求并获取响应
        HttpResponse<String> response = Unirest.post(url)
                .header("Content-Type", "application/json")
                .header("Accept", "*/*")
                .header("Host", IP + ":" + 8080)
                .header("Connection", "keep-alive")
                .body(monitoringParameters)
                .asString(); // 注意这里的 asString()


        String body = response.getBody(); // 将 JSON 字符串转换为 JSONObject
        JSONObject jsonObject = new JSONObject(body);

        // 将 JSONObject 转换为 Map
        Map<String, Object> map = new JSONObject(body).toMap();

        return map;
    }

    @Override
    public boolean recordUpdateHistory(Map<String, Object> monitoringParameters) {
        // 构建参数映射
        HashMap<String, String> parametersMap = new HashMap<>();
        parametersMap.put("ALARMDISTANCE", "报警区范围");
        parametersMap.put("DRIVERDISTANCE", "司机区范围");
        parametersMap.put("SHUTDOWNDISTANCE", "断电区范围");
        parametersMap.put("MINNUMBERSOFPERSON", "最小限制人数");
        parametersMap.put("MAXNUMBERSOFPERSON", "最大限制人数");
        parametersMap.put("WHITELIST", "白名单");  // 新增的键值对

        // 获取修改前后的参数
        Map<String, Object> valuesAfterModified = (Map<String, Object>) monitoringParameters.get("Value");
        Map<String, Object> valuesBeforeModified = (Map<String, Object>) monitoringParameters.get("ValueBeforeModified");

        if (valuesBeforeModified == null || valuesAfterModified == null) {
            return false;
        }

        // 遍历parametersMap中的每个key
        for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
            String key = entry.getKey();
            String parameterName = entry.getValue(); // 记录的参数名称

            // 从修改前后的参数中获取对应的值
            Object valueBefore = valuesBeforeModified.get(key);
            Object valueAfter = valuesAfterModified.get(key);

            // 只有当值不同且存在对应值时才记录
            if (valueBefore != null && !valueBefore.equals(valueAfter)) {
                TDeviceInfoModificationHistory deviceInfoModificationHistory = new TDeviceInfoModificationHistory();
                deviceInfoModificationHistory.setDeviceId("") // 设备ID（根据实际情况填充）
                        .setDeviceName((String) monitoringParameters.get("DeviceName")) // 设备名称（根据实际情况填充）
                        .setDeviceIp((String) monitoringParameters.get("ControllerIP")) // 设备IP（根据实际情况填充）
                        .setParameterOfModification(parameterName) // 修改的参数名称
                        .setTransportProtocol("HTTP")
                        .setTimeOfModification(LocalDateTime.now()) // 修改时间
                        .setUserOfModification(SecurityUtils.getUsername()); // 修改的用户（根据实际情况填充）

                // 处理值的类型
                String valueBeforeStr = convertValueToString(valueBefore);
                String valueAfterStr = convertValueToString(valueAfter);

                deviceInfoModificationHistory.setValueBeforeModification(valueBeforeStr); // 修改前的值
                deviceInfoModificationHistory.setValueAfterModification(valueAfterStr); // 修改后的值

                // 插入修改记录到数据库
                tDeviceInfoModificationHistoryMapper.insertTDeviceInfoModificationHistory(deviceInfoModificationHistory);
            }
        }
        return true;
    }

    // 辅助方法：将值转换为字符串
    private String convertValueToString(Object value) {
        if (value instanceof List) {
            // 如果是 List 类型，使用逗号分隔的字符串
            return String.join(", ", (List<String>) value);
        } else {
            // 否则直接返回值的字符串表示
            return value.toString();
        }
    }


    @Override
    public Map<String, Object> selectMaintenanceMode(TDeviceStatus tDeviceStatus) {

        String deviceIp = tDeviceStatus.getDeviceIp();
        String Status = tDeviceStatus.getDeviceStatus();
        if (Status.equals("在线")){
            String url ="";

            url="http://"+deviceIp+":8080/electronicFence/overhaul";

            // 发送 GET 请求并获取响应
            HttpResponse<String> response = Unirest.get(url)
                    .header("Content-Type", "application/json")
                    .header("Accept", "*/*")
                    .header("Host", deviceIp+":8080")
                    .header("Connection", "keep-alive")
                    .asString();


            String body = response.getBody(); // 将 JSON 字符串转换为 JSONObject
            JSONObject jsonObject = new JSONObject(body);

            // 将 JSONObject 转换为 Map
            Map<String, Object> map = new JSONObject(body).toMap();

            return map;
        }else {
            HashMap<String, Object> map2 = new HashMap<>();
            map2.put("msg","设备离线，无法查看详情");
            map2.put("code",500);
            return map2;
        }



    }

    @Override
    public Map<String, Object> updateMaintenanceMode(Map<String, Object> monitoringParameters) {


        String deviceIp = (String) monitoringParameters.get("deviceIp");
        String deviceStatus = (String) monitoringParameters.get("deviceStatus");
        String State = (String) monitoringParameters.get("State");

        if (deviceStatus.equals("在线")){
            String url ="";

            url="http://"+deviceIp+":8080/electronicFence/overhaul";
            url=url+"?state="+State;
            // 发送 GET 请求并获取响应
            HttpResponse<String> response = Unirest.get(url)
                    .header("Content-Type", "application/json")
                    .header("Accept", "*/*")
                    .header("Host", deviceIp+":8080")
                    .header("Connection", "keep-alive")
                    .asString();


            String body = response.getBody(); // 将 JSON 字符串转换为 JSONObject
            JSONObject jsonObject = new JSONObject(body);

            // 将 JSONObject 转换为 Map
            Map<String, Object> map = new JSONObject(body).toMap();

            return map;
        }else {
            HashMap<String, Object> map2 = new HashMap<>();
            map2.put("msg","设备离线，无法修改详情");
            map2.put("code",500);
            return map2;
        }
    }

    @Override
    public List<TDeviceStatus> selectTDeviceStatusHistoryList(TDeviceStatus tDeviceStatus) {
        return tDeviceStatusMapper.selectTDeviceStatusHistoryList(tDeviceStatus);
    }

    @Override
    public void recordMaintenanceModeUpdateHistory(Map<String, Object> monitoringParameters) {
        String stateAfterModified = (String) monitoringParameters.get("State");
        String stateBeforeModified = (String) monitoringParameters.get("StateBeforeModified");
        if (stateAfterModified != null && stateBeforeModified != null && !stateBeforeModified.equals(stateAfterModified)) {
            TDeviceInfoModificationHistory deviceInfoModificationHistory = new TDeviceInfoModificationHistory();
            deviceInfoModificationHistory.setDeviceId("") // 设备ID（根据实际情况填充）
                    .setDeviceName((String) monitoringParameters.get("deviceName")) // 设备名称（根据实际情况填充）
                    .setDeviceIp((String) monitoringParameters.get("deviceIp")) // 设备IP（根据实际情况填充）
                    .setParameterOfModification("检修模式") // 修改的参数名称
                    .setTransportProtocol("HTTP")
                    .setValueBeforeModification(stateBeforeModified) // 修改前的值
                    .setValueAfterModification(stateAfterModified) // 修改后的值
                    .setTimeOfModification(LocalDateTime.now()) // 修改时间
                    .setUserOfModification(SecurityUtils.getUsername()); // 修改的用户（根据实际情况填充）
            // 插入修改记录到数据库
            tDeviceInfoModificationHistoryMapper.insertTDeviceInfoModificationHistory(deviceInfoModificationHistory);

        }
    }

}
